/**
 * 描述: 业务逻辑处理 - 微信相关接口
 * 作者: 
 * 日期: 
 */
const { getUserDataAsync, parseXmlAsync, formatMessage } = require('../utils/xml-parse-tool')
const sha1 = require('sha1');
const { Token, AppId, AppSecret } = require('../config/index');
const {
    CODE_ERROR,
    CODE_SUCCESS,
    PRIVATE_KEY,
    JWT_EXPIRED,
    COOKIE_TOKEN_EXPIRED
} = require('../utils/constant');
const { ReplyUserMessages } = require('../utils/replyUserMessage');
const wxGetOpenIdService = require('../utils/wxGetOpenId')

function ServerValid() {
    return async(req, res) => {
        const { signature, echostr, timestamp, nonce } = req.query;
        const arr = [timestamp, nonce, Token];
        arr.sort();
        const str = arr.join('');
        const sha1Str = sha1(str);
        //验证消息是否来自服务器
        if (sha1Str === signature) {
            res.send(echostr)
        } else {
            res.end('error')
        }
    }
}
//接收用户信息,并被动回复用户信息
function ReceiveUserInformation() {
    return async(req, res) => {
        const { signature, timestamp, nonce } = req.query;
        const arr = [timestamp, nonce, Token];
        arr.sort();
        const str = arr.join('');
        const sha1Str = sha1(str);
        if (sha1Str !== signature) {
            res.end('error');
        }
        //用户信息处理
        else {
            //接收用户数据函数
            const xmlData = await getUserDataAsync(req);
            //解析数据称js对象
            const jsData = await parseXmlAsync(xmlData);
            //格式化数据
            const message = formatMessage(jsData);
            console.log(message);
            //处理用户信息
            res.end(ReplyUserMessages(message));
            ///用户消息回复结束地方
        }
    }
}

//接受微信服务器发送的code，只能使用一次，5分钟后失效
async function receiveWxCode(req, res) {
    let result = await wxGetOpenIdService.getWxUserOpenId(req.query.code);
    let openid = result.data.openid;
    res.cookie('openid', openid, { signed: false, maxAge: COOKIE_TOKEN_EXPIRED, httpOnly: true })
    res.redirect(302, '/api/userinfo?openid=' + openid);
}

module.exports = { ServerValid, ReceiveUserInformation, receiveWxCode }



/**
 * code 
 * { code: '071QdXkl20Nsj843Imol2GnSVE0QdXkX', state: 'TaskReceipts' }
 * 
 * 
 * 通过code换取的信息是微信服务器封装后的一个对象，其中data对象是我们想要的
 * result.date
 * 
 * {
  access_token: '52_w1v5tqvpm6CWLmc_fnIzrMr925HQQGSQNYzykP1Y99naiLK_dw-9VKIgn0L78MEpamASycLc2ZkD_OLHyNp64mIYkG4zON9IlKvDrrh0KIM',
  expires_in: 7200,
  refresh_token: '52_sUSC7eC2xInALVgeiwse5MceH9E-eTzGzyJmyQ6NzdF9CRg9BC-CX0WHCmU05KA0uBWM_udSwY2yFnhPrITlpJYm6KNwnhMYXsN4mIQA56A',
  openid: 'oPBuf6haO1mR_ASkIFsWdLxobmSE',
  scope: 'snsapi_base'
}
 * 
 * 
 */